package com.leon.proxy.V04;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

/**
 * 动态代理-优点：CGlib方式：codeGenerateLibrary
 * 1.写完基础功能
 * 2.添加辅助功能
 * 3.使用reflect反射包中的proxy.newInstance创建代理对象，再通过代理对象调用

 * @author 史鸿禹
 * @date 2022/07/13  2:54 下午
 */
public class Person {
    public void eat() {
        System.out.println("吃饭");
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

static class MyInterceptor implements MethodInterceptor{

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before");
        Object o1 = methodProxy.invokeSuper(o, objects);
        System.out.println("after");
        return o1;
    }
}

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        //设置需要增强的父类
        enhancer.setSuperclass(Person.class);
        //设置回调方法
        enhancer.setCallback(new MyInterceptor());
        //创建实例
        Person person = (Person)enhancer.create();
        //吃
        person.eat();
    }
}
